use std::{cell::UnsafeCell, mem::MaybeUninit};

use android_logger::Config;
use jni::JavaVM;
use log::LevelFilter;
use tokio::runtime::{Builder, Runtime};

pub struct AppInfo {
    pub vm: JavaVM,
    pub rt: Runtime,
}

static APP_INFO: UninitMutable<AppInfo> = UninitMutable::const_new();


pub fn init(vm: JavaVM) {
    
    android_logger::init_once(Config::default().with_max_level(LevelFilter::Trace));

    let rt = Builder::new_multi_thread()
    .enable_all()
    .build()
    .unwrap();

    let app_info = AppInfo {
        vm,
        rt,
    };

    unsafe { APP_INFO.write(app_info); }
}

pub const fn global_rt() -> &'static Runtime {
    unsafe { &APP_INFO.as_ref().rt }
}

unsafe impl <T: Send> Send for UninitMutable<T> {}
unsafe impl <T: Sync> Sync for UninitMutable<T> {}

pub struct UninitMutable<T> {
    value: UnsafeCell<MaybeUninit<T>>,
}

impl <T> UninitMutable<T> {

    pub const fn const_new() -> Self {
        Self { value: UnsafeCell::new(MaybeUninit::uninit()) }
    }

    pub unsafe fn write(&self, value: T) {
        (&mut *self.value.get()).write(value);
    }

    pub const unsafe fn as_ref(&self) -> &T {
        (&*self.value.get()).assume_init_ref()
    }
}






